package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

type RequestBean struct {
	Url          string `json:"url"`
	Router       string `json:"router"`
	CallbackInfo string `json:"callback_info"`
}

type ServiceInfo struct {
	ServiceName string `json:"service_name"`
	ServiceMsg  string `json:"service_msg"`
}

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func handleRequest(c *gin.Context) {
	var requestBean RequestBean
	_ = c.ShouldBindJSON(&requestBean)

	// 获取url地址进行get请求
	var buffer bytes.Buffer
	buffer.WriteString(requestBean.Url)
	buffer.WriteString(requestBean.Router)
	buffer.WriteString("?callback_info=")
	buffer.WriteString(requestBean.CallbackInfo)
	url := buffer.String()

	fmt.Printf("url %s\n", url)
	resp, err := http.Get(url)

	if err != nil {
		fmt.Printf(err.Error())
		c.JSON(http.StatusOK, Response{-1, err.Error(), map[string]interface{}{}})
	}

	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)

	var service2Bean Response

	_ = json.Unmarshal(result, &service2Bean)

	fmt.Println(service2Bean.Msg)
	c.JSON(http.StatusOK, Response{0, "success", ServiceInfo{"service2", service2Bean.Msg}})
}

func main() {
	r := gin.Default()
	r.POST("/service1", handleRequest)
	_ = r.Run(":8001")
}
